package com.myrslok.set;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class FileTreeResource implements ResourceSet.ResourceSupplier<File> {

    private static final Logger logger = LoggerFactory.getLogger(FileTreeResource.class);

    @NotNull
    private File file;

    public FileTreeResource(@NotNull final String file) {
        this.file = new File(file);
    }

    public FileTreeResource(@NotNull final File file) {
        this.file = file;
    }

    @NotNull
    public File getFile() {
        return file;
    }

    private Set<File> getFiles() {
        final Set<File> files = new HashSet<File>();
        if (!file.exists()) {
            logger.warn(file + " does not exist (absolute path: " + file.getAbsolutePath() + ")");
        } else if (file.isFile()) {
            files.add(file);
        } else if (file.isDirectory()) {
            addFilesInDir(files, file);
        }
        return files;
    }

    private void addFilesInDir(@NotNull final Set<File> files, @NotNull final File dir) {
        for (final File sourceFile : dir.listFiles()) {
            if (sourceFile.isFile()) {
                files.add(sourceFile);
            } else if (sourceFile.isDirectory()) {
                addFilesInDir(files, sourceFile);
            }
        }
    }

    @Override
    public Set<File> getResources() {
        return getFiles();
    }

}
